package com.smartens.boit.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.smartens.boit.MainActivity;
import com.smartens.boit.MyApplication2;
import com.smartens.boit.R;
import com.smartens.boit.activity.FaultFollowActivity;
import com.smartens.boit.activity.FaultHistoryActivity;
import com.smartens.boit.activity.viewmodel.MainActivityViewMode;
import com.smartens.boit.adapter.LatestAdapter;
import com.smartens.boit.adapter.ProcessedAdapter;
import com.smartens.boit.bean.ElectricBean;
import com.smartens.boit.bean.FaultBean;
import com.smartens.boit.bean.ListBean;
import com.smartens.boit.bean.ListBeans;
import com.smartens.boit.bean.ProcessedBean;
import com.smartens.boit.util.FaultDeal;
import com.smartens.boit.util.HttpHelper;
import com.smartens.boit.util.PickerDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description 故障管理
 * @Author songtt
 * @Date 2021/3/4
 */
public class SecondFragment extends Fragment {
    public PickerDialog dialogProfile;
    public FragmentManager fragmentManager;
    private RecyclerView recyclerViewLatest;
    private RecyclerView recyclerViewProcessed;
    private LatestAdapter latestAdapter;
    private ProcessedAdapter processedAdapter;
    private SwipeRefreshLayout mSwipeRefreshLayout;
    private LinearLayoutManager mLinearLayoutManager;
    private LinearLayoutManager pLinearLayoutManager;
    private List<FaultBean> mList = new ArrayList<>();
    private List<ProcessedBean> pList = new ArrayList<>();
    private BroadcastReceiver broadcastReceiver;
    private int pos = 0;
    private MainActivity mainActivity;
    private LinearLayout history;
    private TextView latest;
    private TextView processed;
    private HttpHelper helper;
    public MainActivityViewMode mainActivityViewMode;

    private  void initViewMode()
    {
       mainActivityViewMode= MainActivityViewMode.getViewMode(requireActivity(),requireActivity().getApplication());

    }
    public boolean isErrorC() {
        if (mList.size() > 0) {
            return false;
        } else {
            return true;
        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initViewMode();
        broadcastReceiver = new BroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter();

        // 2. 设置接收广播的类型
        intentFilter.addAction("BROADCAST_ACTION");

        // 3. 动态注册：调用Context的registerReceiver（）方法
        getActivity().registerReceiver(broadcastReceiver, intentFilter);

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().unregisterReceiver(broadcastReceiver);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        Log.v("===加载", "加载了第二个");
        View view = inflater.inflate(R.layout.fragment_second, container, false);
        helper = HttpHelper.getInstance();
        latest = view.findViewById(R.id.tv_latest);
        processed = view.findViewById(R.id.tv_processed);
        recyclerViewLatest = view.findViewById(R.id.rv_latest);
        recyclerViewProcessed = view.findViewById(R.id.rv_processed);
        mSwipeRefreshLayout = view.findViewById(R.id.refresh_layout);
        history = view.findViewById(R.id.fault);
        //   initData();
        mLinearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        pLinearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        latestAdapter = new LatestAdapter(mList,this);
        processedAdapter = new ProcessedAdapter(pList);
        //设置布局管理器
        recyclerViewLatest.setLayoutManager(mLinearLayoutManager);
        recyclerViewProcessed.setLayoutManager(pLinearLayoutManager);
        //设置Adapter
        recyclerViewLatest.setAdapter(latestAdapter);
        recyclerViewProcessed.setAdapter(processedAdapter);
        Log.v("hascodecc_", "recyclerViewLatest" + recyclerViewLatest.hashCode());
        Log.v("hascodecc_", "recyclerViewProcessed" + recyclerViewProcessed.hashCode());
        Log.v("hascodecc_", "latestAdapter" + latestAdapter.hashCode());
        Log.v("hascodecc_", "processedAdapter" + processedAdapter.hashCode());
        //初始化视图
        latestAdapter.setOnItemClickListener(new LatestAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                pos = position;
                Intent intent = new Intent(getActivity(), FaultFollowActivity.class);
                startActivityForResult(intent, 1);
                Log.v("=====", "点击详情");
            }

        });
        history.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), FaultHistoryActivity.class);
                startActivity(intent);
            }
        });
        latest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                latest.setTextColor(Color.parseColor("#547E42"));
                processed.setTextColor(Color.parseColor("#ff555555"));
                recyclerViewLatest.setVisibility(View.VISIBLE);
                recyclerViewProcessed.setVisibility(View.GONE);
            }
        });
        processed.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                latest.setTextColor(Color.parseColor("#ff555555"));
                processed.setTextColor(Color.parseColor("#547E42"));
                recyclerViewLatest.setVisibility(View.GONE);
                recyclerViewProcessed.setVisibility(View.VISIBLE);
            }
        });
        GetProcessedList();
        //实现下拉刷新功能
        handleDownPullUpdate();
        return view;
    }

    public void initData() {
        FaultBean faultBean = new FaultBean();
        faultBean.setName("设备A");
        faultBean.setNumber("16000301277");
        faultBean.setDateTime("故障时间 2020-11-2 17:08");
        faultBean.setStatus(1);
        for (int i = 1; i <= 1; i++) {
            mList.add(faultBean);
        }
    }

    private void handleDownPullUpdate() {
        Log.v("下拉刷新", "=====");
        mSwipeRefreshLayout.setEnabled(true);
//        mTextView.setVisibility(View.VISIBLE);
//        mSwipeRefreshLayout.setColorSchemeResources(R.color.colorAccent,R.color.colorPrimary);
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
//                mTextView.setVisibility(View.VISIBLE);
//                mTextView.setText("下拉刷新");
//                被刷新时的操作
//                更新UI
                if (recyclerViewProcessed.getVisibility() == View.VISIBLE) {
                    GetProcessedList();
                }
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //更新成功后设置UI，停止更新
//                        mTextView.setText("刷新成功！！！");
//                        mTextView.setVisibility(View.GONE);
                        mSwipeRefreshLayout.setRefreshing(false);
                    }
                }, 1500);
            }
        });
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        mainActivity = (MainActivity) context;
    }

    /**
     * 动态注册广播
     */
    @Override
    public void onResume() {
        Log.v("fdsdfsdff", "onResume()");
        super.onResume();
        // 1. 实例化BroadcastReceiver子类 &  IntentFilter

        // refresh();

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            MyApplication2 myApplication2 = (MyApplication2) getActivity().getApplication();
            pList.addAll(myApplication2.beanList);
            switch (resultCode) {
                case 0:
                    mList.get(pos).setStatus(1);
                    break;
                case 1:
                    if (mList.size() > 0 && pos >= 0) {
                        mList.remove(pos);
                        ProcessedBean bean = new ProcessedBean();
                        myApplication2.beanList.add(bean);
                        pList.add(0, bean);
                        processedAdapter.setData(pList);
                        // recyclerViewProcessed.setAdapter(processedAdapter);
                        processedAdapter.notifyDataSetChanged();
                        Log.v("recyclerViewProcessed", pList.size() + "");

                    }
                    break;
            }
            if (mList.size() == 0) {
                MainActivity mainActivity = (MainActivity) getActivity();
                mainActivity.settext3();
            }

            latestAdapter.setData(mList);
            latestAdapter.notifyDataSetChanged();
            // recyclerViewLatest.setAdapter(latestAdapter);
            Log.v("hascodecc_", "recyclerViewLatest___2__" + recyclerViewLatest.hashCode());
            Log.v("hascodecc_", "recyclerViewProcessed___2__" + recyclerViewProcessed.hashCode());
            Log.v("hascodecc_", "latestAdapter___2__" + latestAdapter.hashCode());
            Log.v("hascodecc_", "processedAdapter___2__" + processedAdapter.hashCode());
        }
        int count = mList.size();
        int num = 0;
        for (int i = 0; i < mList.size(); i++) {
            if (mList.get(i).getStatus() != 0) {
                num = num + 1;
            }
        }
        if (count == num) {
            mainActivityViewMode.getIsnewMessage().setValue(false);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        //销毁在onResume()方法中的广播
        //  getActivity().unregisterReceiver(broadcastReceiver);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        Log.v("fragment生命周期", "onDestroyView");
    }

    public class BroadcastReceiver extends android.content.BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String dateTime = intent.getStringExtra("dateTime");
            Log.v("=====", "接收广播" + dateTime);
            FaultBean faultBean = new FaultBean();
            faultBean.setName("demo_01");
            faultBean.setStatus(0);
            faultBean.setNumber("16000301277");
            faultBean.setDateTime(dateTime);
            mList.add(0, faultBean);
            //  latestAdapter.notifyItemInserted(0);
            //  latestAdapter.notifyItemRangeChanged(0, mList.size());
            latestAdapter.setData(mList);
            latestAdapter.notifyDataSetChanged();
        }
    }


    /**
     * 获取已处理列表
     */
    public void GetProcessedList() {
        helper.GetProcessedList(new HttpHelper.HttpCallBack<ProcessedBean>() {
            @SuppressLint("LongLogTag")
            @Override
            public void onSuccess(List<ProcessedBean> result) {
                Log.v("=====GetProcessedList==获取方案成功", String.valueOf(result.size()));
                for (int i = 0; i < result.size(); i++) {
                    result.get(i).setFaultTime("故障时间 " + result.get(i).getFaultTime().replace("/", "-"));
                }
                pList = result;
                MyApplication2 myApplication2 = (MyApplication2) mainActivity.getApplication();
                pList.addAll(0, myApplication2.beanList);
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        processedAdapter.setData(pList);
                        Log.v("recyclerViewProcessed", pList.size() + "");
                        processedAdapter.notifyDataSetChanged();
//                        recyclerViewProcessed.setAdapter(processedAdapter);
                    }
                });
            }

            @SuppressLint("LongLogTag")
            @Override
            public void onFailure(String message) {
                Log.v("=====GetProcessedList==获取方案失败", message);
            }
        });
    }
}